package com.fengmi.portal.service.impl;

import cn.hutool.json.JSONUtil;
import com.fengmi.api.cms.CMSApi;
import com.fengmi.api.goods.GoodsApi;
import com.fengmi.entity.cms.CmsContent;
import com.fengmi.entity.vo.CatCascadeVO;
import com.fengmi.entity.vo.CatHotVo;
import com.fengmi.portal.service.IPortalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PortalService implements IPortalService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CMSApi cmsApi;
    @Autowired
    private GoodsApi goodsApi;
    @Override
    public List<CmsContent> findContentByCatId(String catId) {

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps("menhu:portal:cms");
        Object contentJson =  operations.get(catId);

        if(StringUtils.isEmpty(contentJson)){
            List<CmsContent> contentByCatId = cmsApi.findContentByCatId(catId);
            operations.put(catId, JSONUtil.toJsonStr(contentByCatId));
            return contentByCatId;
        }

        List<CmsContent> cmsContents = JSONUtil.toList((String) contentJson, CmsContent.class);

        return cmsContents;
    }

    @Override
    public List<CatCascadeVO> findCatCascade() {
        BoundValueOperations<String, String> operations = redisTemplate.boundValueOps("menu:portal:goods");
        String catMenuJson = operations.get();
        if(StringUtils.isEmpty(catMenuJson)){
            List<CatCascadeVO> catCascade = goodsApi.findCatCascade();
            operations.set(JSONUtil.toJsonStr(catCascade));
            return catCascade;
        }
        List<CatCascadeVO> catCascadeVOS = JSONUtil.toList(catMenuJson, CatCascadeVO.class);

        return catCascadeVOS;
    }

    @Override
    public List<CatHotVo> findCatHotGoods() {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps("menu:portal:hot");
        List<Object> catHotVoJson = operations.values();
        if(StringUtils.isEmpty(catHotVoJson) || catHotVoJson.size()<=0){
            List<CatHotVo> catHotGoods = goodsApi.findCatHotGoods();
            catHotGoods.forEach(catHotVo -> {
                operations.put(catHotVo.getMallGoodsCat().getId()+"",JSONUtil.toJsonStr(catHotVo));
            });
            return catHotGoods;
        }

        List<CatHotVo> list = catHotVoJson.stream().map(json -> {
            CatHotVo catHotVo = JSONUtil.toBean((String) json, CatHotVo.class);
            return catHotVo;
        }).collect(Collectors.toList());
        return list;
    }
}
